import React from 'react'
import MenuConfig from '@/config'
import type { MenuInfo } from 'rc-menu/lib/interface'
import * as Icon from '@ant-design/icons'
import { useNavigate } from 'react-router-dom'
import { selectMenuList } from '@/store/reducers/tab'
import { Layout, Menu } from 'antd'
import { useAppDispatch } from '@/store/hooks'
import { ChildMenuProp, IconName } from './types'
import { tabListState } from '@/store/reducers/types'
const { Sider } = Layout
// 动态获取icon
const iconToElement = (name: IconName) => React.createElement(Icon[name])
// 处理菜单的数据
const items = MenuConfig.map(item => {
  // 没有子菜单
  const child: ChildMenuProp = {
    key: item.path,
    icon: iconToElement(item.icon as IconName),
    label: item.label
  }
  // 有子菜单
  if (item.children) {
    child.children = item.children.map(element => {
      return {
        key: element.path,
        label: element.label
      }
    })
  }
  return child
})

export default function CommonAside({ collapsed }: { collapsed: boolean }) {
  const navigate = useNavigate()
  const dispatch = useAppDispatch()

  // 添加数据到store
  const setTabsList = (val: tabListState) => {
    dispatch(selectMenuList(val))
  }

  // 点击菜单
  const selectMenu = (e: MenuInfo) => {
    /* 
    TODO: 修改data数据类型
    */
    let data: any
    MenuConfig.forEach(item => {
      // 找到当前的数据
      if (item.path === e.keyPath[e.keyPath.length - 1]) {
        data = item
        // 如果是有二级菜单
        if (e.keyPath.length > 1) {
          data = item.children!.find(child => {
            return child.path === e.key
          })
        }
      }
    })
    setTabsList({
      path: data.path,
      name: data.name,
      label: data.label
    })
    navigate(e.key)
  }

  return (
    <Sider trigger={null} collapsed={collapsed} >
      <h3 className='app-name'>{collapsed ? '后台' : '通用后台管理系统'}</h3>
      <Menu
        theme="dark"
        mode="inline"
        defaultSelectedKeys={['1']}
        items={items}
        style={{
          height: "100%"
        }}
        onClick={selectMenu}
      />
    </Sider>
  )
}
